﻿;(function (factory) {
    if (typeof define === "function" && define.cmd) {
        define('cottery',['jquery'], function(){
			/* factory(require('jquery'));
			 return jQuery; */
            // 返回构造函数
            return factory
        });
    } else {
        // 全局模式
        factory(jQuery);
    }
}(function ($) {
	var Lottery = function (options) {

		//执行中 无法再次启动
		this.starting =false;
		this.option = options;
        this.initValue=0;
		this.len = $(this.option.dom).length;
	};

	Lottery.prototype.start = function (id ,endCall,errorCall) {
		if( this.starting) return;

        this.starting =true;
		var _op = this.option,
            _len = this.len,
            _i = this.getSite($(_op.dom),id),
			//差值
        	dce= this.initValue==0 ? 0 :_len-this.initValue;
		if(_i == -1){
            this.starting=false
            errorCall()
		}else {
            this.circleFnc((_len * _op.circle) + _i+dce,endCall)
        }

	};

	//工具 得出当前位置
	Lottery.prototype.getSite = function ($d, _n) {
		var nI=-1;
        $d.each(function (k) {
			if ($(this).attr("data-lid") == _n) {
				nI = k;
				return false
			}
		});
		return nI
	};

	Lottery.prototype.circleFnc = function (num,endCall) {
		var _this = this, _op = this.option, _len = this.len;

		if (num < 0) {
            _this.starting =false
            endCall($(_op.dom).eq(_this.initValue-1))
		} else {
			setTimeout(function () {
				if (_this.initValue >= _len) {
					_this.initValue = 0;
				}
				_this.SyncView(_this.initValue++);
				_this.circleFnc(--num,endCall)
			}, _op.time)

		}

	};

	Lottery.prototype.SyncView = function (i) {
		var _op = this.option;
		$(_op.dom).eq(i).addClass(_op.active).siblings(_op.dom).removeClass(_op.active);
	};
    window.lottery = Lottery
	return Lottery
}));



